//
// Created by Administrator on 2021/4/6.
//


#include <vector>
#include <iostream>
#include <stack>

using namespace std;

//  Definition for a binary tree node.
// 树节点定义
struct TreeNode {
    int val; // 节点值
    TreeNode *left; // 左子节点
    TreeNode *right; // 右子节点

    TreeNode() : val(0), left(nullptr), right(nullptr) {}

    explicit TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};


class Solution {
public:
    void postorder(TreeNode *t, vector<int> &v) { // 递归函数
        if (t == nullptr) {
            return;
        }
        postorder(t->left, v);
        postorder(t->right, v);
        v.push_back(t->val);
    }

    vector<int> postorderTraversal(TreeNode *root) { // 递归解法
        vector<int> ans;
        postorder(root, ans);
        return ans;
    }
};

class Solution2 {
public:
    vector<int> postorderTraversal(TreeNode *root) { // 迭代
        vector<int> res;
        if (root == nullptr) {
            return res;
        }

        stack<TreeNode *> stk;
        TreeNode *prev = nullptr;
        while (root != nullptr || !stk.empty()) {
            while (root != nullptr) {
                stk.emplace(root);
                root = root->left;
            }
            root = stk.top();
            stk.pop();
            if (root->right == nullptr || root->right == prev) {
                res.emplace_back(root->val);
                prev = root;
                root = nullptr;
            } else {
                stk.emplace(root);
                root = root->right;
            }
        }
        return res;
    }
};


// 二叉树的后序遍历 左 右 中
int main() {
//    [ 1, 4, 2, 3 ];
    auto t4 = TreeNode(4);
    auto t3 = TreeNode(3);
    TreeNode t2 = TreeNode(2, &t3, nullptr);
    TreeNode t1 = TreeNode(1, &t4, &t2);
    auto sol = Solution();
//    auto sol = Solution2();
    vector<int> ans = sol.postorderTraversal(&t1);
//    vector<int> ans =
    for (auto x:ans) {
        cout << x << endl;
    }
    return 0;
}
